package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.TaskAttachmentMapper;
import com.cfswt.tasksystem.mapper.TaskMapper;
import com.cfswt.tasksystem.pojo.entity.TaskAttachment;
import com.cfswt.tasksystem.response.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@CrossOrigin
@RequestMapping("/file")
public class UploadController {
    @Autowired
    private TaskAttachmentMapper taskAttachmentMapper;
    private String dirPath = "d:/appFile";

    @PostMapping("/upload")
    public JsonResult doUpload(MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = simpleDateFormat.format(new Date());
        File dirFile = new File(dirPath + datePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        file.transferTo(new File(dirPath + datePath + fileName));
        return JsonResult.ok("http://222.128.105.112:8000/files" + datePath + fileName);
    }

    @DeleteMapping("/delete/{id}")
    public JsonResult delete(@PathVariable Integer id) {
        TaskAttachment taskAttachment = taskAttachmentMapper.selectAttachmentById(id);
        if(taskAttachment != null){
            File file = new File(taskAttachment.getFilePath());
            if(file.exists()){
                file.delete();
            }
            taskAttachmentMapper.deleteAttachmentById(id);
            return JsonResult.ok();
        }else {
            return JsonResult.error(2002,"文件不存在");
        }
    }
}
